<template>
  <div>
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="单据编号" prop="number">
            <el-input v-model="form.number" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" :disabled="disableForm">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" @click="optType === 'add' ? showStoreModal = true : null" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请支付" prop="applyPayment">
            <el-input v-model="form.applyPayment" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批复金额" prop="approvedAmount">
            <el-input v-model="form.approvedAmount" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="btns" style="padding-bottom: 10px;">
        <el-button type="primary" :disabled="disableForm" @click="addRow">新增行</el-button>
        <el-button type="primary" :disabled="disableForm" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:sequence="{row}">
          <el-input v-model="row.sequence" :disabled="disableForm" />
        </template>
        <template v-slot:fundUse="{row}">
          <el-input v-model="row.fundUse" :disabled="disableForm" />

          <!-- <el-select v-model="row.fundUse" :disabled="disableForm" style="width: 100%;" placeholder="请选择资金用途">
            <el-option v-for="item in paymentFundUse" :key="item.name" :label="item.name" :value="item.value" />
          </el-select> -->
        </template>
        <!-- <template v-slot:accountSubjects="{row}">
          <el-select v-model="row.accountSubjects" :disabled="disableForm" style="width: 100%;" placeholder="请选择会计科目">
            <el-option v-for="item in paymentAccountSubjects" :key="item.name" :label="item.name" :value="item.value" />
          </el-select>
        </template> -->
        <template v-slot:reimbursePersonal="{row}">
          <el-input v-model="row.reimbursePersonal" :disabled="disableForm" />
        </template>
        <template v-slot:reimburseAmount="{row}">
          <el-input v-model="row.reimburseAmount" :disabled="disableForm" />
        </template>
        <template v-slot:invoiceAmount="{row}">
          <el-input v-model="row.invoiceAmount" :disabled="disableForm" />
        </template>
        <template v-slot:applyPayment="{row}">
          <el-input v-model="row.applyPayment" :disabled="disableForm" @input="getApplyPayment" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" :disabled="disableForm" />
        </template>
        <template v-slot:lstAttachment="{row}">
          <a class="com-link" @click="uploaderFielRow(row)">文件数（{{ row.lstAttachment.length }}）</a>
        </template>
      </com-table>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />
    </el-form>
    <div style="visibility:hidden; height: 30px;" />
    <span slot="footer" class="dialog-footer">
      <el-button v-show="displayBtn" type="primary" @click="saveDoc">确 定</el-button>
    </span>
  </div>
</template>

<script>
import { getBankInternalPaymentInfoDetail, updateBankInternalPaymentApprovedAmount } from '@/api/moneyManage'
import { getNextWorkflow } from '@/api/flow'
import { getAreaList } from '@/api/common'
import { paymentFundUse, paymentAccountSubjects, workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'AddBankInternalPaymentInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      displayBtn: false,
      showFileModal: false,
      paymentFundUse,
      paymentAccountSubjects,
      workflowStatus,
      showStoreModal: false,
      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        // number: '',
        projectName: '',
        applyPayment: '',
        approvedAmount: '',
        description: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {
      },
      columns: [
        {
          label: '序号',
          slot: 'sequence',
          width: '70'
        },
        {
          label: '资金用途',
          slot: 'fundUse'
        },
        // {
        //   label: '会计科目',
        //   slot: 'accountSubjects'
        // },
        {
          label: '报销人',
          slot: 'reimbursePersonal'
        },
        {
          label: '报销金额',
          slot: 'reimburseAmount'
        },
        {
          label: '发票金额',
          slot: 'invoiceAmount'
        },
        {
          label: '申请支付',
          slot: 'applyPayment'
        },
        {
          label: '备注',
          slot: 'remark'
        },
        {
          label: '附件',
          slot: 'lstAttachment'
        }
      ],
      showTargetSetListModal: false,
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'change' }
        ],
        approvedAmount: [
          { required: true, message: '请输入批复金额', trigger: 'change' }
        ]
      },
      detailRules: {
        // sequence: [
        //   { required: true, message: '请输入序号', trigger: 'change' }
        // ],
        reimbursePersonal: [
          { required: true, message: '请输入报销人', trigger: 'change' }
        ],
        reimburseAmount: [
          { required: true, message: '请输入报销金额', trigger: 'change' }
        ],
        // invoiceAmount: [
        //   { required: true, message: '请输入发票金额', trigger: 'change' }
        // ],
        applyPayment: [
          { required: true, message: '请输入申请支付', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: [],
      fileList: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
    // fileList: {
    //   get() {
    //     return this.uploadRow ? this.uploadRow.lstAttachment : []
    //   },
    //   set(val) {
    //
    //     this.uploadRow.lstAttachment = val
    //   }
    // }
  },
  watch: {
    data: {
      handler(newData, oldData) {
        if (newData.id) {
          this.getDocDetail(newData.businessId)
          const { id } = this.data
          if (!id) return
          const params = {
            startWorkflowId: id
          }
          getNextWorkflow(params).then(res => {
            const { code } = res
            if (code !== '0001') {
              this.displayBtn = true
            } else {
              this.displayBtn = false
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    // this.getRegionData()
  },
  methods: {
    // 获取申请支付
    getApplyPayment() {
      let sum = 0
      this.detailDataList.forEach(item => {
        if (item.applyPayment) {
          sum += Number.parseFloat(item.applyPayment)
        }
      })
      this.form.applyPayment = sum.toFixed(2)
    },
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          sequence: '',
          fundUse: '',
          accountSubjects: '',
          reimbursePersonal: '',
          reimburseAmount: '',
          invoiceAmount: '',
          applyPayment: '',
          remark: '',
          lstAttachment: []
        }
      ]
      this.detailDataList.forEach((element, index) => {
        element.sequence = index + 1
      })
    },
    getStoreSelectedData(type, data) {
      if (type === 'store') {
        this.form.projectName = data.contractName
      }
    },
    uploaderFielRow(row) {
      this.uploadRow = row
      this.fileList = row.lstAttachment
      this.showFileModal = true
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push({
            ...item,
            lstAttachment: []
          })
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
      let sum = 0
      this.detailDataList.forEach(element => {
        sum = sum + element.applyPayment * 1
      })
      this.form.applyPayment = sum
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
      this.detailDataList.forEach((element, index) => {
        element.sequence = index + 1
      })
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getBankInternalPaymentInfoDetail({ bankInternalPaymentInfoId: id }).then(res => {
        const { lstBankInternalPaymentDetail, bankInternalPaymentInfo } = res.data || {}
        if (lstBankInternalPaymentDetail && lstBankInternalPaymentDetail.length > 0) {
          this.detailDataList = lstBankInternalPaymentDetail.map(item => {
            return {
              ...item.bankInternalPaymentDetail,
              lstAttachment: item.lstAttachment
            }
          })
        }
        Object.keys(this.form).forEach(key => {
          const source = bankInternalPaymentInfo[key]
          if (typeof source === 'boolean') {
            this.form[key] = source ? 1 : 0
          } else {
            this.form[key] = source
          }
        })
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            bankInternalPaymentInfoId: this.data.businessId,
            approvedAmount: this.form.approvedAmount
          }
          updateBankInternalPaymentApprovedAmount(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
::v-deep .el-form-item__label{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;

}
.dialog-footer {
  padding-left: 45%;
}
</style>
